#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
from __future__ import print_function
from .. import myprint
from .. import global_dict

# 用来实现动态缓存获得的图像，
# 使得当网络不好时返回上一次网络完好的结果
import functools
def cache_image(get_image_from_net):
    cached = dict()
    cached["image"] = None

    @functools.wraps(get_image_from_net)
    def cache_get_image_from_net(*args,**kwargs):
        image = get_image_from_net(*args,**kwargs)
        if image is None:
            if cached["image"] is None:
                return cache_get_image_from_net(*args,**kwargs)
            else:
                return cached["image"]
        else:
            cached["image"] = image
            return cached["image"]

# 实现单例模式方式一
class Singleton(object):
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            orig = super(Singleton, cls)
            cls._instance = orig.__new__(cls, *args, **kw)
        return cls._instance

# 单例修饰器
def singleton(cls, *args, **kw):
    instances = {}
    def _singleton():
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return _singleton

# 因为数据库模型对象在提交后会失效等问题
# 用一个全局的单例的代理管理器来统一管理
# proxy 实例,用一个字典实现,
# 要求 proxy 的名称必须是全局唯一的,
# 结合 cam的name,nao的name都是全局唯一来使用
@singleton
class ProxyManger():
    def __init__(self):
        self._proxys={}

    def has(self,proxy_name):
        return proxy_name in self._proxys

    def add(self,name,proxy):
        if self.has(name):
            raise ValueError, "Already exits " + name
        self._proxys[name] = proxy

    def get(self,name):
        if not self.has(name):
            raise ValueError, "Not exits " + name
        return self._proxys[name]

    def delete(self,name):
        if not self.has(name):
            raise ValueError, "Not exits " + name
        del self._proxys[name]

proxyManger = ProxyManger()

from . import Nao, Cam, Image, Motion
